package com.imooc.sell.controller;

import com.imooc.sell.dataobject.AbstractStat;
import com.imooc.sell.dataobject.SellByDay;
import com.imooc.sell.dto.StatRateDTO;
import com.imooc.sell.service.StatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpRequest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@RequestMapping("/stat")
@Controller
public class StatController {

    private SimpleDateFormat sdf;

    @Autowired
    private StatService statService;

    /**
     * 统计数据(触发器触发)
     * 指定每天凌晨2点0分0秒统计
     */
    @Scheduled(cron = "0 0 ? 1/1 * ?")
    public void dayStat() {
        try {
            statService.stat();
        } catch (Exception e) {
            log.error("{}数据统计失败" + this.getClass());
        }
    }

    /**
     * 默认访问这个接口
     * 计算数据变化率并获取所有已有的统计数据
     */
    @RequestMapping("/admin/list")
    public ModelAndView totalStat(HttpServletRequest request, Model model) {
        String dateStart = "";
        String dateEnd = "";
        String openid = "";
        //设置默认值
        int page = 1;
        int size = 2;
        int type = 0;
        try {
            dateStart = request.getParameter("dateStart");
            dateEnd = request.getParameter("dateEnd");
            openid = request.getParameter("openid");
            page = Integer.valueOf(request.getParameter("page"));
            size = Integer.valueOf(request.getParameter("size"));
        } catch (Exception e) {
            log.error("{}未指定page:{},size:{}", getClass(), page, size);
        }
        try {
            type = Integer.valueOf(request.getParameter("type"));
        } catch (Exception e) {
            log.error("{}type:{}", getClass(), type);
        }

        dateStart = ((dateStart != null && !"".equals(dateStart)) ? dateStart : "2000-01-01");
        dateEnd = ((dateEnd != null && !"".equals(dateEnd)) ? dateEnd : "2030-01-01");
        //统计变化率
        StatRateDTO dto = statService.statChangeRate();
        sdf = new SimpleDateFormat("yyyy-MM-dd");
        //查询开始时间
        Date dateBeginning = null;
        //查询截止时间
        Date dateEnding = null;
        try {
            dateBeginning = sdf.parse(dateStart);
            dateEnding = sdf.parse(dateEnd);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Pageable pageable = new PageRequest(page - 1, size);
        Page<?> pages = statService.findList(type, pageable, dateBeginning, dateEnding);
        List<String> dateList = new ArrayList<>();
        List<String> sellSuccessList = new ArrayList<>();
        List<String> successSaleList = new ArrayList<>();
        List<String> sellCancelList = new ArrayList<>();
        List<String> sellPaybackList = new ArrayList<>();
        List<?> statList = statService.findAll(type);
        AbstractStat ab = null;
        pickData(dateList, sellSuccessList, successSaleList, sellCancelList, sellPaybackList, statList);
        model.addAttribute("type", type);
        model.addAttribute("dateStart", dateStart);
        model.addAttribute("dateEnd", dateEnd);
        model.addAttribute("openid", openid);
        model.addAttribute("currentPage", page - 1);
        model.addAttribute("size", size);
        model.addAttribute("pageList", pages);
        model.addAttribute("dateList", dateList);
        model.addAttribute("sellSuccessList", sellSuccessList);
        model.addAttribute("successSaleList", successSaleList);
        model.addAttribute("sellCancelList", sellCancelList);
        model.addAttribute("sellPaybackList", sellPaybackList);
        model.addAttribute("statData", dto);
        return new ModelAndView("/statistics/stat");
    }

    private void pickData(List<String> dateList, List<String> sellSuccessList, List<String> successSaleList, List<String> sellCancelList, List<String> sellPaybackList, List<?> statList) {
        AbstractStat ab;
        for (int i = 0; i < statList.size(); i++) {
            ab = (AbstractStat) statList.get(i);
            ab.upToDad();
            dateList.add(sdf.format(ab.getDate()));
            sellSuccessList.add(String.valueOf(ab.getSellSuccess()));
            successSaleList.add(String.valueOf(ab.getSuccessSale()));
            sellCancelList.add(String.valueOf(ab.getSellCancel()));
            sellPaybackList.add(String.valueOf(ab.getSellPayback()));

        }
    }


    /**
     * 测试freemarker
     */
    @RequestMapping("/test")
    public ModelAndView test(Model model, HttpSession session) {
        List list = new ArrayList<>();
        list.add(new SellByDay(1, new BigDecimal(2), 3, 4));
        list.add(new SellByDay(1, new BigDecimal(2), 3, 4));
        list.add(new SellByDay(1, new BigDecimal(2), 3, 4));
        model.addAttribute("list", list);
        return new ModelAndView("/statistics/stat");
    }
}
